package com.tbit.uqbike.center.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.center.config.ThreadPoolConfig.MsgRunnable;
import com.tbit.uqbike.center.pojo.TerPosition;
import com.tbit.uqbike.center.service.MachineStatusService;
import com.tbit.uqbike.center.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.concurrent.ThreadPoolExecutor;

@Service("queueListenter")
@Slf4j
public class QueueListenter {
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    @Qualifier("msgThreadPoolExecutor")
    private ThreadPoolExecutor msgThreadPoolExecutor;

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", 40003);
        TerPosition terPosition = new TerPosition();
        terPosition.setPointType(-1);
        terPosition.setMachineNO("003412345");
        terPosition.setDt(DateTimeUtil.getNowTime());
        terPosition.setLon(113.2541254);
        terPosition.setLat(25.325412);
        terPosition.setCarStatus(7820);
        jsonObject.put("data", terPosition);
        System.out.println(jsonObject);
    }

    //	两种方式 一种与rabbit配置中的bean id挂钩 好处是 不用写@PropertySource
//	@RabbitListener(queues = {"#{mqQueueTerPosition.name}"},concurrency = "5")
    @RabbitListener(queues = {"${mq.queue.ter_position}", "${mq.queue.ter_battery}", "${mq.queue.ter_lithium}"}, concurrency = "10")
    @RabbitHandler
    public void onMessage(Message msg) {
        try {
            String respMsg = new String(msg.getBody(), "UTF-8");
            msgThreadPoolExecutor.execute(new MsgRunnable(respMsg,machineStatusService));
        } catch (Exception e) {
            log.error("center消费者同步终端终态数据异常",e);
        }

    }

    /**
     * 注意此处，因为只有本实例调用了msgThreadPoolExecutor，多个实例需要修改
     */
    @PreDestroy
    public void shutdownExecutor(){
        msgThreadPoolExecutor.shutdown();
    }
}
